package middleware

import (
	"jianianhua-server/services"
	"jianianhua-server/utils"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// AuthMiddleware JWT认证中间件
func AuthMiddleware(wechatService *services.WechatService) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取Authorization header
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			utils.ErrorResponse(c, http.StatusUnauthorized, "缺少认证token")
			c.Abort()
			return
		}

		// 检查Bearer前缀
		tokenString := strings.TrimPrefix(authHeader, "Bearer ")
		if tokenString == authHeader {
			utils.ErrorResponse(c, http.StatusUnauthorized, "token格式错误")
			c.Abort()
			return
		}

		// 验证token
		claims, err := wechatService.ValidateToken(tokenString)
		if err != nil {
			utils.ErrorResponse(c, http.StatusUnauthorized, "token无效或已过期")
			c.Abort()
			return
		}

		// 从claims中获取用户ID
		userIDFloat, ok := (*claims)["user_id"].(float64)
		if !ok {
			utils.ErrorResponse(c, http.StatusUnauthorized, "token中缺少用户ID")
			c.Abort()
			return
		}

		// 将用户ID存储到上下文中
		c.Set("user_id", uint(userIDFloat))
		c.Next()
	}
}

// OptionalAuthMiddleware 可选认证中间件（不强制要求登录）
func OptionalAuthMiddleware(wechatService *services.WechatService) gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.Next()
			return
		}

		tokenString := strings.TrimPrefix(authHeader, "Bearer ")
		if tokenString == authHeader {
			c.Next()
			return
		}

		claims, err := wechatService.ValidateToken(tokenString)
		if err == nil {
			// 从claims中获取用户ID
			if userIDFloat, ok := (*claims)["user_id"].(float64); ok {
				c.Set("user_id", uint(userIDFloat))
			}
		}

		c.Next()
	}
}
